# -*- coding: utf-8 -*-
#   数据库表说明
# @Time    ： 2024/4/7  21:50
# @Auther  ： 徐良
# File     :  tableAndFieldPanel.py
from PySide6.QtCore import Qt, Slot
from baseClass.baseQWidget import BaseQWidget
from baseModule.ui.tableAndFieldUI import Ui_Form
from utils.ebWork import EBWork
from share.bioDialog import Infomation
from share.modelFunction import getMaxRecrodByModel, getFselFIdByModel, clearFelByConditionForModel, \
    removeRecordAndReSetFxh, removeRecord, checkModelsIsDirty, getTableModelBySql
from share.delegateFunction import getConfigDelegate
from share.sqlFunction import getInsertSql, addWhereFentityid, getDelChildSql, getDelParentSqlList, \
    getUpdateSqlList, getUpdateSqlListByModelFIdList, getInsertAndUpdateSqlList
from share.baseFunction import quote
from share.dataFactory import SqlForSave
from PySide6.QtWidgets import QMessageBox, QTableView
import share.globalvar as gol


class TableAndFieldPanel(BaseQWidget, EBWork, Ui_Form):
    """
    数据库表说明
    """
    def __init__(self, msDict, parent=None):
        super(TableAndFieldPanel, self).__init__()
        self.queryPanel = None
        self.setAttribute(Qt.WA_StyledBackground)
        self.setupUi(self)
        self.toolbarFlag = 'browse'
        self.stackedW = "Yes"
        self.baseDbType = gol.getValue('baseDbType')
        self.pFId = -1
        msDict = eval(msDict)
        print(msDict)
        self.doInitWork(msDict)

        self.parentTableView.clicked.connect(self.onParentTableViewClicked)
        self.readParentTable()
        self.readChildTable(-1)

        self.saveActionSignal.connect(self.setToolbarSaveButton)

    def onCheckBoxRow(self, idx):
        """
        勾选事件发生
        :param idx:
        :return:
        """
        self.parentTableView.setCurrentIndex(idx)
        self.onParentTableViewClicked(idx)

    def setLbl_info(self, row):
        """
        设置父表记录
        :return:
        """
        fnumber = self.parentModel.record(row).value('FNumber')
        fname = self.parentModel.record(row).value('FName')
        self.lbl_info.setText(f"记录号：{row + 1}  编码：{fnumber}   名称：{fname}")

    def readParentTable(self):
        """
        读取主表数据
        :return:
        """
        fieldList = self.getS2_FFieldList().copy()
        fieldList.insert(0, '0 as Fsel')

        sql = "select  {fieldStr}  from t_tableDescribe order by FNumber".format(fieldStr=','.join(fieldList))

        fieldNameList = self.getS2_FFieldNameList().copy()
        fieldNameList.insert(0, '选择')

        alignList = self.getS2_FAlignList().copy()
        alignList.insert(0, 'center')


        pdic = {'sql': sql, 'baseDbType': self.baseDbType,
                'fieldNameList': fieldNameList, 'alignList': alignList}

        self.parentModel = getTableModelBySql(pdic)
        self.parentTableView.setModel(self.parentModel)

        isVisibleList = self.getS2_FVisibleList().copy()
        isVisibleList.insert(0, 1)

        widthList = self.getS2_FWidthList().copy()
        widthList.insert(0, 45)

        self.parentTableView.setHideColumnForCol(isVisibleList)
        self.parentTableView.setColumnWidthForList(widthList)

        isEditList = self.getS2_FIsEditList().copy()
        isEditList.insert(0, 1)
        widgetList = self.getS2_FWidgetList().copy()
        widgetList.insert(0, 'check')

        pdic = {'selOption': 0, 'isEditList': isEditList,
                'widgetList': widgetList}

        self.delegateTop = getConfigDelegate(pdic)
        self.delegateTop.checkBoxSignal.connect(self.onCheckBoxRow)
        self.parentTableView.setItemDelegate(self.delegateTop)
        self.parentModel.dataChangedSignal.connect(self.onModelDataChanged)

    def readChildTable(self, fid):
        """
        读取字段表
        :return:
        """
        fieldList = self.getS6_FFieldList()
        fieldNameList = self.getS6_FFieldNameList()
        alignList = self.getS6_FAlignList().copy()

        sql = "select {fieldStr} from t_tableDescribeEntity order by FXh".format(fieldStr=','.join(fieldList))

        sql = addWhereFentityid(sql, fid)

        pdic = {'sql': sql, 'baseDbType': self.baseDbType,
                'fieldNameList': fieldNameList, 'alignList': alignList}
        self.childModel = getTableModelBySql(pdic)
        self.childTableView.setModel(self.childModel)

        visibleList = self.getS6_FVisibleList()
        self.childTableView.setHideColumnForCol(visibleList)
        widthList = self.getS6_FWidthList()
        self.childTableView.setColumnWidthForList(widthList)

        isEditList = self.getS6_FIsEditList()
        widgetList = self.getS6_FWidgetList()
        print(widgetList)

        pdic = {'selOption': 0, 'isEditList': isEditList,
                'widgetList': widgetList}

        delegateBottom = getConfigDelegate(pdic)
        self.childTableView.setItemDelegate(delegateBottom)
        self.childModel.dataChangedSignal.connect(self.onModelDataChanged)

    def onParentTableViewClicked(self, index):
        """
        主表点击事件
        :param index:
        """
        if index.isValid():

            self.parentRow = index.row()
            self.setLbl_info(self.parentRow)
            clearFelByConditionForModel(self.parentModel, self.parentRow)
            self.pFId = self.parentModel.record(self.parentRow).value('FId')
            if self.pFId == '':
                next_index = self.parentTableView.model().index(index.row(), index.column())
                if next_index.isValid():
                    self.parentTableView.setCurrentIndex(next_index)
                return

            self.readChildTable(self.pFId)
            # 设置当前单元格为可编辑状态
            # 先断开数据变化的信号
            self.parentModel.dataChangedSignal.disconnect(self.onModelDataChanged)
            self.parentTableView.edit(index)  # idx是当前选中的索引 否则会不进入编辑状态
            # 再连接信号
            self.parentModel.dataChangedSignal.connect(self.onModelDataChanged)

            # 设置下一个单元格的索引
            next_index = self.parentTableView.model().index(index.row(), index.column())
            if next_index.isValid():
                self.parentTableView.setCurrentIndex(next_index)

    def actionSelect(self, q):
        """
        工具栏命令事件
        :param q:
        """
        sel = q.text()
        if sel == '增加':
            self.parentAdd()
        elif sel == '删除':
            self.parentDel()
        elif sel == '过滤':
            print('parent', self.parentModel.dirty)
            print('child', self.childModel.dirty)
        elif sel == '保存':
            self.save()

    def save(self):
        """
        保存单据
        """
        sqlList = []
        pfidList = list(self.parentModel.listUpdate)
        if len(pfidList) > 0:

            pdic = {'tableName': 't_tableDescribe', 'fidList': pfidList, 'model': self.parentModel,
                    'fieldList': ['FId', 'FNumber', 'FName', 'FTableName', 'FDescribe', 'FBelongto', 'FSystem'],
                    'typeList': ['Integer', 'String', 'String', 'String', 'String', 'String', 'Integer'],
                    'joinList': [0, 1, 1, 1, 1, 1, 1]}

            sqlList = getUpdateSqlListByModelFIdList(pdic)


        cfidList = list(self.childModel.listUpdate)
        print(cfidList)
        ss = []
        if len(cfidList) > 0:
            pdic = {'tableName': 't_tableDescribeEntity', 'fidList': cfidList, 'model': self.childModel,
                    'fieldList': ['FID', 'FEntityId', 'FXh', 'FField', 'FFieldName', 'FFieldType',
                                  'FJoinSql', 'FWidget', 'FAlign', 'FWidth', 'FIsEdit', 'FVisible'],
                    'typeList': ['Integer', 'Integer', 'Integer', 'String', 'String', 'String', 'Integer',
                                 'String', 'String', 'Integer', 'Integer', 'Integer'],
                    'joinList': [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}

            ss = getUpdateSqlListByModelFIdList(pdic)

        sqlList.extend(ss)

        ok = SqlForSave.execSqlList(sqlList, self.baseDbType)
        if ok['ret']:
            # 重读数据
            self.readParentTable()
            self.readChildTable(self.pFId)
            self.parentModel.listUpdate.clear()
            self.childModel.listUpdate.clear()
            self.parentModel.dirty = False
            self.childModel.dirty = False
            self.setToolbarSaveButton(0)  # 设置【保存按钮】
        else:
            Infomation.info(ok['info'])

    def parentAdd(self):
        """
        父表增加记录
        :return:
        """
        sql = getInsertSql('t_tableDescribe', 'FNumber', quote('00.00'))
        ok = SqlForSave.execSqlList([sql], self.baseDbType)
        if ok['ret']:
            # 重读数据
            self.readParentTable()
            self.setToolbarSaveButton(0)
        else:
            Infomation.info(ok['info'])

    def parentDel(self):
        """
        删除父表勾选记录
        :return:
        """
        # 判断是否需要先保存
        if self.checkSave():
            ok = Infomation.question('数据已更改，是否需要保存？')
            if ok == QMessageBox.Yes:
                return

        # 获取父表Fid
        fid, rec = getFselFIdByModel(self.parentModel)
        if fid == '-1':
            Infomation.info('请勾选主表记录')
            return

        sqlList = getDelParentSqlList('t_tableDescribe', fid, ['t_tableDescribeEntity'])
        # 移除model中指定记录
        removeRecord(self.parentModel, rec)
        ok = SqlForSave.execSqlList(sqlList, self.baseDbType)
        if ok['ret']:
            # 重读数据
            self.readParentTable()
            self.readChildTable('-1')
            self.setToolbarSaveButton(0)
        else:
            Infomation.info(ok['info'])

    def execChildSql(self, sqlList, pFid):
        """
        执行子表的sql语句
        :param sqlList:
        :param pFid:
        :return:
        """
        ok = SqlForSave.execSqlList(sqlList, self.baseDbType)
        if ok['ret']:
            # 重读数据
            self.readChildTable(pFid)
            modelList = [self.parentModel, self.childModel]
            self.setToolbarSaveButton(checkModelsIsDirty(modelList))  # 设置【保存按钮】

            last_index = self.childModel.index(self.childModel.rowCount() - 1, 3)
            self.childTableView.scrollTo(last_index, QTableView.PositionAtBottom)
            self.childTableView.update(last_index)

        else:
            Infomation.info(ok['info'])

    @Slot()
    def on_btn_add_clicked(self):
        """
        编辑格式增加
        :return:
        """
        if self.checkSave():
            ok = Infomation.question('数据已更改，是否需要保存？')
            if ok == QMessageBox.Yes:
                return
        # 获取父表Fid
        self.pFId, rec = getFselFIdByModel(self.parentModel)
        if self.pFId == '-1':
            Infomation.info('请勾选主表记录')
            return

        fxh = str(getMaxRecrodByModel(self.childModel) + 1)

        sql = getInsertSql('t_tableDescribeEntity', 'FEntityId, FXh', self.pFId + ',' + fxh)
        self.execChildSql([sql], self.pFId)

    @Slot()
    def on_btn_insert_clicked(self):
        """
        编辑格式插入
        :return:
        """
        # 获取父表Fid
        self.pFId, pRow = getFselFIdByModel(self.parentModel)
        if self.pFId == '-1':
            Infomation.info('请勾选主表记录')
            return

        index = self.childTableView.currentIndex()
        if index.isValid():
            row = index.row()

            col = self.childModel.getColForField('fxh')

            self.childModel.insertRows(row, 1)
            idx = self.childModel.index(row, col)
            ifxh = row + 1
            self.childModel.setData(idx, ifxh)

            # 加上父ID
            pcol = self.childModel.getColForField('fentityid')
            pidx = self.childModel.index(row, pcol)
            self.childModel.setData(pidx, self.pFId)

            end = self.childModel.rowCount()
            row = row + 1
            ifxh += 1
            for irow in range(row, end):
                idx = self.childModel.index(irow, col)
                self.childModel.setData(idx, irow + 1)

            pdic = {'tableName': 't_tableDescribeEntity', 'model': self.childModel,
                    'fieldList': ['FID', 'FEntityId', 'FXh', 'FField', 'FFieldName', 'FFieldType', 'FJoinSql'],
                    'typeList': ['Integer', 'Integer', 'Integer', 'String', 'String', 'String', 'String'],
                    'joinList': [0, 1, 1, 1, 1, 1, 1]}

            sqlList = getInsertAndUpdateSqlList(pdic)
            ok = SqlForSave.execSqlList(sqlList, self.baseDbType)
            if ok['ret']:
                # 重读数据
                self.readChildTable(self.pFId)
                self.childModel.listUpdate.clear()
                self.childModel.dirty = False
            else:
                Infomation.info(ok['info'])
        else:
            Infomation.info('请选择子表的指定行')

    @Slot()
    def on_btn_del_clicked(self):
        """
        子表删除
        :return:
        """
        if self.checkSave():
            ok = Infomation.question('数据已更改，是否需要保存？')
            if ok == QMessageBox.Yes:
                return

        index = self.childTableView.currentIndex()
        if index.isValid():
            row = index.row()
            ask = Infomation.question(f"删除行号 {self.childModel.record(row).value('FXh')}, 字段名为"
                                      f" {self.childModel.record(row).value('FField')} 的记录？")
            if ask == QMessageBox.Yes:
                sqlList = []
                fid = self.childModel.record(row).value('FId')
                sql = getDelChildSql('t_tableDescribeEntity', str(fid))
                sqlList.append(sql)
                pFid = self.childModel.record(row).value('FEntityId')
                # 处理model, 处理序号
                removeRecordAndReSetFxh(self.childModel, row)
                fieldList = ['FID', 'FEntityId', 'FXh', 'FField', 'FFieldName', 'FFieldType', 'FJoinSql']
                typeList = ['Integer', 'Integer', 'Integer', 'String', 'String', 'String', 'String']
                joinSqlList = [0, 1, 1, 1, 1, 1, 1]
                ssList = getUpdateSqlList('t_tableDescribeEntity', self.childModel, fieldList, typeList, joinSqlList)
                sqlList.extend(ssList)

                self.execChildSql(sqlList, pFid)

            else:
                return
        else:
            Infomation.info('请选定要删除的字段表行')


if __name__ == '__main__':
    import sys
    from PySide6.QtWidgets import QApplication, QMessageBox

    app = QApplication(sys.argv)
    dic = "{'msFNumber': '71.01', 'msClass': '10', 'msSaveType':1}"
    window = TableAndFieldPanel(dic)
    window.show()
    sys.exit(app.exec())
